package io.kiki.sba.registry.trace;

import java.io.Serializable;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

public final class TraceId implements Serializable {
    private static final transient UUID SEED = UUID.randomUUID();
    private static final transient String SEED_PREFIX = Long.toHexString(SEED.getMostSignificantBits()) + Long.toHexString(SEED.getLeastSignificantBits()) + '-';
    private static final transient AtomicLong SEQ = new AtomicLong();

    private final long mostSigBits;
    private final long leastSigBits;
    private final long seq;

    private transient volatile String string;

    private TraceId(long most, long least, long seq) {
        this.mostSigBits = most;
        this.leastSigBits = least;
        this.seq = seq;
    }

    public static TraceId newTraceID() {
        return new TraceId(SEED.getMostSignificantBits(), SEED.getLeastSignificantBits(), SEQ.incrementAndGet());
    }


    private String createString() {
        if (SEED.getMostSignificantBits() == mostSigBits && SEED.getLeastSignificantBits() == leastSigBits) {
            return SEED_PREFIX + seq;
        }
        StringBuilder sb = new StringBuilder(64);
        sb.append(Long.toHexString(mostSigBits)).append(Long.toHexString(leastSigBits)).append('-').append(seq);
        return sb.toString();
    }
}
